package com.simple.modules.sys.controller;

import com.simple.common.utils.ProComFileUtil;
import com.simple.common.utils.R;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Map;

@RestController
@RequestMapping("/sys/common")
public class SysCommonController extends AbstractController {

    @GetMapping("/readFileOnline")
    public R readFileOnline(@RequestParam("fileUrl") String fileUrl, HttpServletResponse response) throws Exception {
        File file = new File(fileUrl);
        ProComFileUtil.onlineReadFile(response, file);
        return R.ok();
    }

    @DeleteMapping("/deleteFile")
    public R deleteFile(@RequestParam("fileUrl") String fileUrl) {
        ProComFileUtil.deleteFile(fileUrl);
        return R.ok();
    }

    @PostMapping("/downloadFile")
    public R downloadFile(@RequestBody Map<String, Object> params
            , HttpServletResponse response) throws Exception {
        ProComFileUtil.downloadZipFile(response, params);
        return R.ok();
    }

    @GetMapping("/downloadTemp")
    public R downloadTemp(HttpServletResponse response, @RequestParam("fileName") String fileName) throws Exception {
        Resource resource = new ClassPathResource("temp/" + fileName);
        int i = fileName.indexOf(".");
        String prefix = fileName.substring(0,i);
        String suffix = fileName.substring(i);
        // 创建临时文件
        File tempFile = File.createTempFile(prefix, suffix);
        try (InputStream inputStream = resource.getInputStream();
             FileOutputStream outStream = new FileOutputStream(tempFile)) {
            // 将资源文件内容写入临时文件
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
        }
        ProComFileUtil.onlineReadFile(response,tempFile);
        tempFile.delete();
        return R.ok();
    }
}
